import { Message } from "element-ui";
import Vue from "vue";
import VueRouter from "vue-router";
// import HomeView from "../views/HomeView.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "login",
    component: () => import("@/views/user/LoginView.vue"),
  },
  {
    path: "/about",
    name: "about",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  },
  {
    path: "/admin",
    meta: { requireAuth: true },
    name: "admin",
    component: () => import("@/views/admin/AdminView.vue"),
    children: [
      {
        name: "dash",
        path: "dash",
        component: () => import("@/views/admin/DashView.vue"),
      },
      {
        name: "orderlist",
        path: "orderlist",
        component: () => import("@/views/admin/order/OrderList.vue"),
      },
      // 如果没有自定义路由，跳转到dash页面
      {
        path: "",
        redirect: "dash",
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

export default router;

// 路由权限信息
router.beforeEach((to, from, next) => {
  // 如果需要权限
  if (to.meta.requireAuth) {
    // 是否有token
    if (localStorage.getItem("token")) {
      // 有token放行
      next();
    } else {
      // 如果没有跳转到首页
      Message({
        message: "需要先登录",
        type: "warning",
      });
      next("/?redirect=" + to.path);
    }
  } else {
    // 如果没有权限就放行
    next();
  }
});
